package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author Liu
 * @date 2025-03-29
 */
@Service
@RequiredArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    private final ElderMapper elderMapper;

    private final BedMapper bedMapper;

    private final ContractMapper contractMapper;

    private final CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = selectCheckInById(id);
        if(ObjectUtil.isEmpty(checkIn)){
            throw new BaseException("入住信息不存在");
        }
        //1.封装家庭成员
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> list =null;
        if(ObjectUtil.isNotEmpty(remark)){
          list=JSONUtil.toList(remark, ElderFamilyVo.class);
        }

        //2.封装入住配置  根据配置表中关联的入住表中的id来查询配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        if(ObjectUtil.isNotEmpty(checkInConfig)){
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        }
        //3.封装老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkIn.getIdCardNo()));
        BeanUtils.copyProperties(elder, checkInElderVo);
        //4.封装合同信息
         Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(list);

        return checkInDetailVo;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.判断老人是否已经入住
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, idCardNo));
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new BaseException("老人已入住");
        }
        //2.更新床位信息为已入住
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        if(ObjectUtil.isEmpty(bed)){
            throw new BaseException("床位不存在");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.保存或更新老人数据
        Elder elder1 = saveOrUpdateElder(bed, checkInApplyDto.getCheckInElderDto());

        //4.新增入住信息
        CheckIn checkIn = insertElderCheckIn(elder1, checkInApplyDto,bed);


        //5.新增入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);

        //6.新增签约办理信息
        //生成合同编号
        String contractNum = "HT" + CodeGenerator.generateContractNumber();
        saveContract(checkInApplyDto.getCheckInContractDto(), elder1, contractNum, checkInApplyDto.getCheckInConfigDto());

    }

    /**
     * 新增入住信息
     *
     * @param elder1
     * @param checkInApplyDto
     * @param bed
     * @return
     */
    private CheckIn insertElderCheckIn(Elder elder1, CheckInApplyDto checkInApplyDto, Bed bed) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder1.getId());
        checkIn.setElderName(elder1.getName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        //根据床位id找到床位编号
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setSortOrder(0);
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setIdCardNo(elder1.getIdCardNo());
        insertCheckIn(checkIn);
        return checkIn;
    }

    /**
     * 保存签约办理信息
     *
     * @param checkInContractDto
     * @param elder1
     * @param contractNum
     * @param checkInConfigDto
     */
    private void saveContract(CheckInContractDto checkInContractDto, Elder elder1, String contractNum, CheckInConfigDto checkInConfigDto) {
        Contract contract = new Contract();
        //封装属性
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setElderId(Integer.valueOf(elder1.getId().toString()));
        contract.setElderName(elder1.getName());
        contract.setContractNumber(contractNum);
        //判断合同状态
        LocalDateTime startDate = checkInConfigDto.getStartDate();
        LocalDateTime endDate = checkInConfigDto.getEndDate();
        if (checkInContractDto.getSignDate().isBefore(startDate)) {
            contract.setStatus(0);
        } else if (checkInContractDto.getSignDate().isAfter(endDate)) {
            contract.setStatus(2);
        } else {
            contract.setStatus(1);
        }
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //插入数据
        contractMapper.insert(contract);
    }

    /**
     * 保存或更新老人信息
     *
     * @param bed
     * @param checkInElderDto
     */
    private Elder saveOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        //查询老人信息如果存在则修改 如果不存在则新增
        Elder elder1 = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, elder.getIdCardNo()));
        if (ObjectUtil.isNotEmpty(elder1)) {
            elder.setId(elder1.getId());
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }
}
